package com.guo.hui.service;

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.guo.hui.model.NoteBook;
import com.guo.hui.util.MongoManager;
import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;

@Service("noteBookService")
public class NoteBookServiceImpl {

	// @Autowired
	// private MongoTemplate mongoTool;

	public NoteBook getNote(String id) {
		NoteBook nt = new NoteBook();
		MongoCollection<Document> db = MongoManager.getCollection("note");
		BasicDBObject query = new BasicDBObject();
		query.put("_id", new ObjectId(id));
		FindIterable<Document> iterable = db.find(query);
		Document doc = iterable.first();
		nt.setNote(doc.getString("note"));
		nt.setTitle(doc.getString("title"));
		nt.setTime(doc.getString("time"));
		nt.setId(doc.get("_id").toString());
		return nt;
	}

	public List<NoteBook> getNoteData() {
		MongoCollection<Document> db = MongoManager.getCollection("note");
		BasicDBObject noback = new BasicDBObject();
		noback.put("_id", 1);
		noback.put("title", 1);
		noback.put("note", 1);
		noback.put("time", 1);
		BasicDBObject query = new BasicDBObject();
		FindIterable<Document> iterable = db.find(query).projection(noback);
		List<NoteBook> list = new ArrayList<>();
		for (Document dd : iterable) {
			NoteBook nb = new NoteBook();
			nb.setNote(dd.getString("note"));
			nb.setTitle(dd.getString("title"));
			nb.setTime(dd.getString("time"));
			nb.setId(dd.get("_id").toString());
			list.add(nb);
		}
		return list;
	}

	public void updatesave(String note) {
		NoteBook nb = JSONObject.toJavaObject(JSONObject.parseObject(note), NoteBook.class);
		BasicDBObject doc = new BasicDBObject();
		doc.put("_id", new ObjectId(nb.getId()));
		BasicDBObject data = new BasicDBObject();
		data.put("title", nb.getTitle());
		data.put("note", nb.getNote());
		BasicDBObject update = new BasicDBObject();
		update.put("$set", data);
		MongoCollection<Document> db = MongoManager.getCollection("note");
		db.updateOne(doc, update);
	}

	public void save(String note) {
		if (!StringUtils.isEmpty(note)) {
			MongoCollection<Document> db = MongoManager.getCollection("note");
			db.insertOne(new Document().parse(note));
			// try {
			// JSONObject obj = new JSONObject(note);
			// NoteBook tb = new NoteBook();
			// tb.setNote(obj.get("note").toString());
			// tb.setTitle(obj.get("title").toString());
			// mongoTool.save(tb);
			// } catch (JSONException e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }

		}

	}

}
